package com.cloudbroker.bcs.platform.ltb.middle.task.base;

import java.util.concurrent.ExecutorService;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cloudbroker.bcs.common.thread.ExecutorServiceManager;
import com.cloudbroker.bcs.common.zookeeper.ZooKeeperClient;

public abstract class SimpleLeaderTakeTask {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(SimpleLeaderTakeTask.class);
    
    private static final String TASK_LEADER_COMPETITION_PATH_BASE = "/biz/task/leader";
    
    @Resource
    protected ZooKeeperClient zkClient;
    
    protected String taskTypeId;
    
    protected String taskLeaderCompetitionPath;
    
    @PostConstruct
    public void init() {
        taskTypeId = getClass().getName();
        taskLeaderCompetitionPath = getTaskLeaderCompetitionPath(taskTypeId);
        // 先初始化竞争
        isThisNodeLeader();
    }
    
    protected String getTaskLeaderCompetitionPath(String taskTypeId) {
        return ZooKeeperClient.buildFullPath(TASK_LEADER_COMPETITION_PATH_BASE, taskTypeId);
    }
    
    protected boolean isThisNodeLeader() {
        return zkClient.thisNodeIsLeader(taskLeaderCompetitionPath);
    }
    
    public void execute() {
        if (isThisNodeLeader()) {
            ExecutorService executorService = ExecutorServiceManager.getCachedThreadPool("HSBCPSSysTask");
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        doTask();
                    } catch (Exception e) {
                        LOGGER.error("execute task failed: " + taskTypeId);
                    }
                }
            });
            /*Collection<String> tenantIds = ConfigUtil.getTenantIds();
            for (final String tenantId : tenantIds) {
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        DataContext.setTenantId(tenantId);
                        try {
                            doTask();
                        } catch (Exception e) {
                            LOGGER.error("execute task failed: " + taskTypeId + " for " + tenantId);
                        } finally {
                            DataContext.clear();
                        }
                    }
                });
            }*/
        }
    }
    
    public abstract void doTask();
    
}
